package com.wubo.common.web;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.json.JSONUtil;

/**
 * 
 * @author WuBo
 * @CreateDate 2012-2-16
 */
public class JsonUtils {
	public static String CHARSET = "UTF-8";
	
	public static String toString(Object json){
		try{
			return JSONUtil.serialize(json, null, null, false, false);
		}catch(Exception e){
			throw new RuntimeException("序列化对象【"+json+"】时出错", e);
		}
	}
	
	public static void write(String json, OutputStream os){
		write(json, CHARSET, os);
	}
	/**
	 * 提交到一个IFrame时，返回的JSON为IFrame的内容，但由于IE下的编码采用本地编码（比如是zh_CN），
	 * 可能出现乱码问题，这里需要明确指定IFrame的编码
	 * @author WuBo
	 * @CreateDate 2012-3-19 下午02:39:50
	 * @param json
	 * @param isIFrame
	 */
	public static void write(String json, boolean isIFrame, OutputStream os){
		if(isIFrame){
			write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset="+CHARSET+"\" /></head><body>"+json+"</body></html>", os);
		}
		write(json, CHARSET, os);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T[] toArray(Class<T> entityClass, String jsonString){
		JSONArray json = JSONArray.fromObject(jsonString);
		return (T[])JSONArray.toArray(json, entityClass);
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T toBean(Class<T> entityClass, String jsonString){
		JSONObject json = JSONObject.fromObject(jsonString);
		return (T)JSONObject.toBean(json, entityClass);
	}

	public static void write(String json, String charset, OutputStream os){
		BufferedOutputStream bos = null;
		try{
			bos = new BufferedOutputStream(os);
			bos.write(json.getBytes(charset));
		}catch(IOException ie){
			throw new RuntimeException("Occur an error when write json to response !");
		}finally{
			if(bos!=null){
				try{bos.close();}catch(Exception e){}
			}
			if(os!=null){
				try{os.close();}catch(Exception e){}
			}
		}
	}
}
